<template>
    <div class="scroll-container" ref="messageContainer" > 
      
      <div 
        v-for="(msg, index) in currentMessages" 
        :key="index"
        :class="['message-bubble', msg.sender === 'me' ? 'sent' : 'received']">
        <div class="avatar">
          <el-avatar :src="msg.avatar"></el-avatar>
        </div>
        <div class="message-content">
          <div class="message-text">{{ msg.text }}</div>
          <div class="message-time">{{ msg.time }}</div>
        </div>
      </div>
    </div>
</template>

<script setup lang="ts">
import {chatStore} from '@/stores/disk/chat';
import { nextTick, ref, watch,computed} from 'vue';
const chatStor=chatStore();
const currentMessages=computed(()=>{
  return chatStor.state.messages.filter(msg => msg.contactId === chatStor.state.currentContact.id)
})

// 添加自动滚动到底部逻辑
const messageContainer = ref<HTMLElement>();
watch(chatStor.state.messages, async () => {
  await nextTick(); // 等待DOM更新
  if (messageContainer.value) {
    messageContainer.value.scrollTo({
      top: messageContainer.value.scrollHeight,
      behavior: 'smooth'
    });
  }
}, { deep: true, immediate: true });
</script>

<style scoped>
.scroll-container {
  overflow-y: auto;
  padding: 20px;
  overflow:auto;
  height: calc(100vh - 160px); /* 根据实际布局调整高度 */
  display: flex;
  flex-direction: column;
  gap: 12px;
}
.avatar{
  margin-left: -15px;
}
.message-bubble {
  max-width: 70%;
  margin-bottom: 5px;
  display: flex;
}
.message-content {
  padding: 12px 16px;
  border-radius: 6px;
  position: relative;
}
.message-time {
  font-size: 12px;
  color: rgba(255,255,255,0.8);
  margin-top: 4px;
  text-align: right;
}
.sent {
  margin-left: auto;
  justify-content: flex-end;
  flex-direction: row-reverse; /* 新增，让自己发的消息头像在右侧 */
}
.sent .avatar {
  margin-left: 0;
  margin-right: -20px; /* 新增，调整右侧头像的外边距 */
}
.sent .message-content {
  background: #409eff;
  color: white;
  border-radius: 12px 12px 0 12px;
}

.received .message-content {
  background: #f5f7fa;
  color: #303133;
  border-radius: 12px 12px 12px 0;
}
.received .message-time {
  color: #909399;
}
</style>